package cn.com.qiter.eduorder.controller;


import cn.com.qiter.common.Result;
import cn.com.qiter.common.ordervo.UcenterMemberOrder;
import cn.com.qiter.common.vo.ProjectModel;
import cn.com.qiter.common.vo.QrcodeModel;
import cn.com.qiter.eduorder.client.DictionaryClient;
import cn.com.qiter.eduorder.client.UcenterClient;
import cn.com.qiter.eduorder.entity.TrafficControl;
import cn.com.qiter.eduorder.entity.vo.TrafficQuery;
import cn.com.qiter.eduorder.entity.vo.TrafficVo;
import cn.com.qiter.eduorder.service.TrafficControlService;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * <p>
 * 交通工程业务表 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2021-04-15
 */
@RestController
@RequestMapping("/eduorder/traffic")
public class TrafficControlController {
    //把service注入
    @Autowired
    private TrafficControlService trafficControlService;

    @Autowired
    private DictionaryClient dictionaryClient;

    @Autowired
    private UcenterClient ucenterClient;

    //1 查询讲师表所有数据
    //rest风格
    @ApiOperation(value = "所有防治列表")
    @GetMapping("findAll")
    public Result findAll() {
        //调用service的方法实现查询所有的操作
        List<TrafficControl> list = trafficControlService.list(null);
        return Result.ok().data("items",list);
    }

    //2 逻辑删除讲师的方法
    @ApiOperation(value = "逻辑删除防治")
    @DeleteMapping("remove/{id}")
    public Result remove(@ApiParam(name = "id", value = "ID", required = true)
                         @PathVariable String id) {
        boolean flag = trafficControlService.removeById(id);
        if(flag) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }

    //3 分页查询讲师的方法
    //current 当前页
    //limit 每页记录数
    @GetMapping("page/{current}/{limit}")
    public Result page(@PathVariable long current,
                       @PathVariable long limit) {
        //创建page对象
        Page<TrafficControl> page = new Page<>(current,limit);

        //调用方法实现分页
        //调用方法时候，底层封装，把分页所有数据封装到pageTeacher对象里面
        trafficControlService.page(page,null);

        long total = page.getTotal();//总记录数
        List<TrafficControl> records = page.getRecords(); //数据list集合

        return Result.ok().data("total",total).data("rows",records);
    }

    //4 条件查询带分页的方法
    @PostMapping("pageCondition/{current}/{limit}")
    public Result pageCondition(@PathVariable long current, @PathVariable long limit,
                                @RequestBody(required = false) TrafficQuery query) {
        //创建page对象
        Page<TrafficControl> pageTeacher = new Page<>(current,limit);

        //构建条件
        QueryWrapper<TrafficControl> wrapper = new QueryWrapper<>();
        // 多条件组合查询
        // mybatis学过 动态sql
        String deviceId = query.getDeviceId();
        String begin = query.getBegin();
        String end = query.getEnd();
        String codeNumber = query.getCodeNumber();
        String userId = query.getUserId();
        String projectId = query.getProjectId();
        //判断条件值是否为空，如果不为空拼接条件
        if(!StringUtils.isEmpty(deviceId)) {
            //构建条件
            wrapper.like("device_id",deviceId);
        }
        if(!StringUtils.isEmpty(begin)) {
            wrapper.ge("stime",begin);
        }
        if(!StringUtils.isEmpty(end)) {
            wrapper.le("stime",end);
        }

        if(!StringUtils.isEmpty(userId)) {
            wrapper.eq("user_id",userId);
        }
        if(!StringUtils.isEmpty(projectId)) {
            wrapper.eq("project_id",projectId);
        }
        if(!StringUtils.isEmpty(codeNumber)) {
            wrapper.eq("codeNumber",codeNumber);
        }
        //排序
        wrapper.orderByDesc("stime");

        ObjectMapper mapper = new ObjectMapper();
        //调用方法实现条件查询分页
        trafficControlService.page(pageTeacher,wrapper);

        long total = pageTeacher.getTotal();//总记录数
        List<TrafficControl> records = pageTeacher.getRecords(); //数据list集合
        List<TrafficVo> record = new ArrayList<>();
        for (TrafficControl pc :
                records) {
            TrafficVo vo = new TrafficVo();
            BeanUtil.copyProperties(pc,vo);
            Result qrcode = ucenterClient.getByName(pc.getQrcode());
            LinkedHashMap lhm = (LinkedHashMap) qrcode.getData().get("teacher");
            cn.com.qiter.common.vo.QrcodeModel qm = mapper.convertValue(lhm, QrcodeModel.class);
            vo.setQrcodeModel(qm);
            UcenterMemberOrder ucenter = ucenterClient.getUserInfoOrder(pc.getUserId());
            vo.setUcenterMemberModel(ucenter);
            Result  project = ucenterClient.getProjectById(pc.getProjectId());
            LinkedHashMap plhm = (LinkedHashMap) project.getData().get("teacher");
            ProjectModel pm = mapper.convertValue(plhm,ProjectModel.class);
            vo.setProjectModel(pm);
            record.add(vo);
        }
        return Result.ok().data("total",total).data("rows",record);
    }

    //添加讲师接口的方法
    @PostMapping("add")
    public Result add(@RequestBody TrafficControl eduTeacher) {
        String str = eduTeacher.getUserId();
        Result project = ucenterClient.getOneDeleted(str);
        LinkedHashMap lhm = (LinkedHashMap) project.getData().get("teacher");
        String id = (String) lhm.get("id");
        eduTeacher.setProjectId(id);
        boolean save = trafficControlService.save(eduTeacher);
        if(save) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }

    //根据讲师id进行查询
    @GetMapping("getDictByName/{name}")
    public Result getDictByName(@PathVariable String name) {
        Result result = dictionaryClient.getByName(name);
        return Result.ok().data("dict",result);
    }
    //根据讲师id进行查询
    @GetMapping("get/{id}")
    public Result get(@PathVariable String id) {
        TrafficControl eduTeacher = trafficControlService.getById(id);
        return Result.ok().data("teacher",eduTeacher);
    }
    //根据讲师id进行查询
    @GetMapping("getByQrcode/{qrcode}")
    public Result getByQrcode(@PathVariable String qrcode) {
        QueryWrapper<TrafficControl> wrapper = new QueryWrapper<>();
        wrapper.eq("qrcode",qrcode);
        //wrapper.last("LIMIT 1");
        List<TrafficControl> eduTeacher = trafficControlService.list(wrapper);
        return Result.ok().data("trap",eduTeacher);
    }
    //讲师修改功能
    @PostMapping("update")
    public Result update(@RequestBody TrafficControl eduTeacher) {
        boolean flag = trafficControlService.updateById(eduTeacher);
        if(flag) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }


    /**
     *
     * @param day
     * @return
     */
    @GetMapping("countDay/{day}")
    public Result countDay(@PathVariable String day) {
        Integer count = trafficControlService.countDay(day);
        return Result.ok().data("countDay",count);
    }
}

